; This NSIS script is based on several NSIS Example Scripts distributed with
; NSIS and written by Joost Verbung

;--------------------------------
;Includes

  !include "MUI2.nsh"        ; Modern UI
  !include "FileFunc.nsh"    ; File functions

;--------------------------------
;General

  ;Name and file
  Name "Google Reader Notifier Qt"
  OutFile "GoogleReaderNotifierQt Installer.exe"

  ;Icons
  !define MUI_ICON "data\icons\installer\grnotifqt_inst.ico"
  !define MUI_UNICON "data\icons\uninstaller\grnotifqt_uninst.ico"

  ;Default installation folder
  InstallDir "$PROGRAMFILES\Google Reader Notifier Qt"

  ;Get installation folder from registry if available
  InstallDirRegKey HKLM "Software\Google Reader Notifier Qt" ""

  ;Request application privileges for Windows Vista
  RequestExecutionLevel admin

;--------------------------------
; Variables
  var StartMenuFolder
  var delInstDir
  var uninstWhileInstalling

;--------------------------------
;Interface Settings

  !define MUI_ABORTWARNING
  !define MUI_CUSTOMFUNCTION_UNABORT un.Abort

;--------------------------------
;Pages

  !insertmacro MUI_PAGE_LICENSE "install_dir\COPYING.txt"
  !insertmacro MUI_PAGE_DIRECTORY

  ; Start Menu folder pge cnfiguration
  !define MUI_STARTMENUPAGE_REGISTRY_ROOT "HKCU"
  !define MUI_STARTMENUPAGE_REGISTRY_KEY "Software\Google Reader Notifier Qt"
  !define MUI_STARTMENUPAGE_REGISTRY_VALUENAME "Start Menu Folder"

  !insertmacro MUI_PAGE_STARTMENU Application $StartMenuFolder

  !insertmacro MUI_PAGE_INSTFILES

  !define MUI_FINISHPAGE_NOAUTOCLOSE

  !define MUI_FINISHPAGE_RUN "$INSTDIR\bin\GoogleReaderNotifierQt.exe"
  !define MUI_FINISHPAGE_RUN_TEXT "Run Google Reader Notifier Qt"
  !insertmacro MUI_PAGE_FINISH

  !insertmacro MUI_UNPAGE_CONFIRM
  !insertmacro MUI_UNPAGE_INSTFILES

;--------------------------------
;Languages
 
  !insertmacro MUI_LANGUAGE "English"

;--------------------------------
;Custom macros

!macro UninstallFiles
  RMDir /r "$INSTDIR\bin"
  RMDir /r "$INSTDIR\data"
  Delete "$INSTDIR\*.*"
IntCmp $delInstDir 0 +2
  RMDir "$INSTDIR"
!macroend

!macro UninstallShortcuts
  Delete "$SMPROGRAMS\$StartMenuFolder\*.*"
  RMDir "$SMPROGRAMS\$StartMenuFolder"
!macroend

!macro UninstallRegistry
  DeleteRegKey /ifempty HKLM "Software\Google Reader Notifier Qt"
!macroend

Function uninstallFiles
  !insertmacro UninstallFiles
FunctionEnd
Function uninstallShortcuts
  !insertmacro UninstallShortcuts
FunctionEnd
Function uninstallRegistry
  !insertmacro UninstallRegistry
FunctionEnd

Function un.installFiles
  !insertmacro UninstallFiles
FunctionEnd
Function un.installShortcuts
  !insertmacro UninstallShortcuts
FunctionEnd
Function un.installRegistry
  !insertmacro UninstallRegistry
FunctionEnd

;--------------------------------
;Installer Sections

Function .onInit
  StrCpy $delInstDir 1
FunctionEnd

Section "Dummy Section" SecDummy

  SetOutPath "$INSTDIR"

  ; Try to terminate (using force) the app if it's running
  ; NOTE This terminates _all_ instances, not only the installed ones
  ; TODO Make this terminate only the installed one
  DetailPrint "Killing all GoogleReaderNotifierQt.exe instances..."
  ; ExecWait 'taskkill /F /IM GoogleReaderNotifierQt.exe'
  nsExec::Exec "taskkill /F /IM GoogleReaderNotifierQt.exe"
  ClearErrors

  ; Uninstalling previous install if it exists
  FindFirst $0 $1 $INSTDIR\Uninstall.exe
  FindClose $0
  StrCmp $1 "" noPreviousInstall hasPreviousInstall
  hasPreviousInstall:
  DetailPrint "Uninstalling previous installation..."
  FileOpen $0 "$INSTDIR\uninstall_lock" "w"
  IfErrors 0 noErrors0
    DetailPrint "Couldn't create lock file $INSTDIR\uninstall_lock. Aborting."
    Abort "Couldn't uninstall previous installation: cannot write to $INSTDIR"
  noErrors0:
  FileClose $0
  nsExec::Exec '"$INSTDIR\Uninstall.exe" /S /NO_DEL_INSTDIR /WHILE_INSTALLING'
  IfErrors 0 lockLoop
    DetailPrint "Couldn't open $INSTDIR\Uninstall.exe. Aborting."
    Abort "Couldn't uninstall previous installation. Installation failed."
  lockLoop:
  IfFileExists "$INSTDIR\uninstall_lock" 0 outOfLockLoop
    Sleep 200
    Goto lockLoop
  outOfLockLoop:
  IfFileExists "$INSTDIR\uninstall_success" uninstallOk 0
    DetailPrint "Couldn't uninstall previous installation. Aborting..."
    Abort "Couldn't uninstall previous installation or user canceled."
  uninstallOk:
  Delete "$INSTDIR\uninstall_success"
  ClearErrors
  DetailPrint "Uninstallation of previous installation done."
  noPreviousInstall:
  ClearErrors

  File /r install_dir\*.*
  IfErrors 0 noErrors1
    DetailPrint "An error was found. Aborting installation. Cleaning up..."
    Call uninstallFiles
    Abort "Couldn't copy files to the installation folder. Installation failed."
  noErrors1:

  ;Store installation folder
  WriteRegStr HKLM "Software\Google Reader Notifier Qt" "" $INSTDIR
  IfErrors 0 noErrors2
    DetailPrint "An error was found. Aborting installation. Cleaning up..."
    Call uninstallFiles
    Call uninstallRegistry
    Abort "Couldn't add a key to the registry. Installation failed."
  noErrors2:

  ;Create uninstaller
  WriteUninstaller "$INSTDIR\Uninstall.exe"
  IfErrors 0 noErrors3
    DetailPrint "An error was found. Aborting installation. Cleaning up..."
    Call uninstallFiles
    Call uninstallRegistry
    Abort "Couldn't create an uninstaller. Installation failed."
  noErrors3:

  SetOutPath "$INSTDIR\bin"

  ; Create start menu shortcuts
  !insertmacro MUI_STARTMENU_WRITE_BEGIN Application
    CreateDirectory "$SMPROGRAMS\$StartMenuFolder"
    CreateShortCut "$SMPROGRAMS\$StartMenuFolder\Google Reader Notifier.lnk" "$INSTDIR\bin\GoogleReaderNotifierQt.exe"
    CreateShortCut "$SMPROGRAMS\$StartMenuFolder\Settings Cleaner.lnk" "$INSTDIR\bin\SettingsCleaner.exe"
    CreateShortCut "$SMPROGRAMS\$StartMenuFolder\Uninstall Google Reader Notifier Qt.lnk" "$INSTDIR\Uninstall.exe"
  !insertmacro MUI_STARTMENU_WRITE_END
  IfErrors 0 noErrors4
    DetailPrint "An error was found. Aborting installation. Cleaning up..."
    Call uninstallFiles
    Call uninstallShortcuts
    Call uninstallRegistry
    Abort "Couldn't create shortcuts. Installation failed."
  noErrors4:

  SetOutPath "$INSTDIR"
  
  ; Write uninstall information to Add/remove programs
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt" "DisplayName" "Google Reader Notifier Qt"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt" "DisplayVersion" "1.0.91"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt" "UninstallString" "$\"$INSTDIR\Uninstall.exe$\""
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt" "QuietUninstallString" "$\"$INSTDIR\Uninstall.exe$\" /S"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt" "DisplayIcon" "$INSTDIR\Uninstall.exe,0"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt" "UrlInfoAbout" "http://code.google.com/p/google-reader-notifier-qt/"
  WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt" "NoModify" 0x1
  WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt" "NoRepair" 0x1

SectionEnd

;--------------------------------
;Descriptions

  ;Language strings
  LangString DESC_SecDummy ${LANG_ENGLISH} "A test section."

  ;Assign language strings to sections
  !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
    !insertmacro MUI_DESCRIPTION_TEXT ${SecDummy} $(DESC_SecDummy)
  !insertmacro MUI_FUNCTION_DESCRIPTION_END

;--------------------------------
;Uninstaller Sections

Function un.onInit
  ; Get command line parameters
  ${GetParameters} $0
  ${GetOptions} $0 "/NO_DEL_INSTDIR" $1
  IfErrors 0 unsetIt
    StrCpy $delInstDir 1
    Goto foobarbar
  unsetIt:
  StrCpy $delInstDir 0
  foobarbar:
  ${GetOptions} $0 "/WHILE_INSTALLING" $1
  IfErrors 0 setIt2
    StrCpy $uninstWhileInstalling 0
    Goto onInitEnd
  setIt2:
  StrCpy $uninstWhileInstalling 1
  onInitEnd:
FunctionEnd

Function un.Abort
  IntCmp $uninstWhileInstalling 1 0 abortEnd abortEnd
    Delete "$INSTDIR\uninstall_lock"
  abortEnd:
FunctionEnd

Section "Uninstall"
  ; Ask if the user wants to delete settings
  MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to delete the current user's Google Reader Notifier Qt settings? The settings of other users must be deleted manually." /SD IDNO IDYES deleteSettings IDNO justContinue
  deleteSettings:
  ; This delete's the current user's Google Reader Notifier Qt settings
  DetailPrint "Deleting settings from current user..."
  ExecWait '"$INSTDIR\bin\SettingsCleaner.exe" --silent'
  Goto skipTempUnsetAutostart
  justContinue:
  DetailPrint "Temporarily disabling autostart..."
  ExecWait '"$INSTDIR\bin\SettingsCleaner.exe" --temp-unset-autostart-only'
  skipTempUnsetAutostart:
  Var /GLOBAL hadErrors
  StrCpy $hadErrors 0

  IfErrors 0 +5
    MessageBox MB_OK|MB_ICONEXCLAMATION "Couldn't remove/clean settings."
	StrCpy $hadErrors 1
	ClearErrors

  ; Try to terminate (using force) the app if it's running
  ; NOTE This terminates _all_ instances, not only the installed ones
  ; TODO Make this terminate only the installed one
  DetailPrint "Killing all GoogleReaderNotifierQt.exe instances..."
  ; ExecWait 'taskkill /F /IM GoogleReaderNotifierQt.exe'
  nsExec::Exec "taskkill /F /IM GoogleReaderNotifierQt.exe"
  ClearErrors

  Call un.installFiles
  IfErrors 0 +5
    MessageBox MB_OK|MB_ICONEXCLAMATION "Couldn't delete some of the files in $INSTDIR."
    StrCpy $hadErrors 1
    ClearErrors

  !insertmacro MUI_STARTMENU_GETFOLDER Application $StartMenuFolder
  Call un.installShortcuts
  IfErrors 0 +5
    MessageBox MB_OK|MB_ICONEXCLAMATION "Couldn't uninstall start menu shortcuts."
    StrCpy $hadErrors 1
    ClearErrors

  Call un.installRegistry
  IfErrors 0 +5
    MessageBox MB_OK|MB_ICONEXCLAMATION "Couldn't delete some registry keys."
    StrCpy $hadErrors 1
    ClearErrors

  IntCmp $hadErrors 1 hadErrors
  Goto hadNoErrors
  hadErrors:
    MessageBox MB_OK|MB_ICONEXCLAMATION "Some files or items couldn't be uninstalled. Please remove them manually."
    SetErrorLevel 2
  hadNoErrors:
  
  DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GoogleReaderNotifierQt"

  IntCmp $uninstWhileInstalling 1 doSth uninstEnd uninstEnd
  doSth:
  IntCmp $hadErrors 0 uninstSuccess uninstFail uninstFail
  uninstSuccess:
  DetailPrint "Writing uninstall_success file"
  FileOpen $0 "$INSTDIR\uninstall_success" "w"
  FileClose $0
  uninstFail:
  DetailPrint "Deleting lock file"
  Delete "$INSTDIR\uninstall_lock"
  uninstEnd:
SectionEnd